package com.rich.dmr.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rich.dmr.R;
import com.rich.dmr.common.RichStaggeredGridLayoutManager;
import com.rich.dmr.model.ChannelModel;
import com.rich.dmr.model.MessageEvent;
import com.rich.dmr.ui.activity.MainActivity;
import com.rich.dmr.ui.view.CommonDialog;
import com.rich.dmr.ui.view.SimpleToolbar;
import com.rich.dmr.utils.ConvertUtils;
import com.rich.dmr.utils.DataBaseUtils;
import com.rich.dmr.utils.Log;
import com.rich.dmr.utils.SoundPoolUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rich.dmr.DmrManager;

public class ChannelFragment extends Fragment implements View.OnClickListener {
    private String TAG = "rich---ChannelFragment";
    private List<ChannelModel> channelModels = new ArrayList<>();
    private ChannelListGridAdapter adapter;
    private Context mContext;
    private DataBaseUtils mDataBaseUtils;
    private DmrManager dmrManager;
    private TextToSpeech mSpeech;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        Log.d(TAG, "onAttach");
    }


    @SuppressLint("WrongConstant")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        mDataBaseUtils = DataBaseUtils.getInstance(mContext);
        channelModels.addAll(mDataBaseUtils.findChannelList());
        dmrManager = (DmrManager) mContext.getSystemService("dmrservice");
        mSpeech = new TextToSpeech(mContext, new TTSListener());
        //mSpeech.setPitch(0.5f);
        //mSpeech.setSpeechRate(0.5f);
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false, priority = 0)
    public void handleData(MessageEvent messageEvent) {
        Log.d(TAG, "handleData msg="+messageEvent.getMsg());
        int index = messageEvent.getIndex();
        Log.d(TAG, "handleData index="+index);
        if(messageEvent.getMsg() == 1){
            //mSpeech.speak(channelModels.get(index).getNameChannel(), TextToSpeech.QUEUE_FLUSH, null);
            channelModels.clear();
            channelModels.addAll(mDataBaseUtils.findChannelList());
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View root = inflater.inflate(R.layout.fragment_channel_list, container, false);
        SimpleToolbar simpleToolbar = root.findViewById(R.id.channel_list_tools_bar);
        simpleToolbar.setMainTitle("Channel list");
        simpleToolbar.setLeftTitleDrawable(R.mipmap.icon_left);
        simpleToolbar.setLeftTitleClickListener(this);
        simpleToolbar.setRightTitleDrawable(R.mipmap.icon_plus);
        simpleToolbar.setRightTitleClickListener(this);
        final RecyclerView recyclerView = root.findViewById(R.id.channel_list);
        recyclerView.setLayoutManager(new RichStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        adapter = new ChannelListGridAdapter();
        recyclerView.setAdapter(adapter);
        return root;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated");
    }

    @Override
    public void onViewStateRestored(Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        Log.d(TAG, "onViewStateRestored");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d(TAG, "onSaveInstanceState");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mSpeech.stop();
        mSpeech.shutdown();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "onDetach");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Log.d(TAG, "onLowMemory");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Log.d(TAG, "onTrimMemory");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_left_title:
                ((MainActivity) getActivity()).getViewPager().setCurrentItem(1);
                break;
            case R.id.txt_right_title:
                initDialog();
                break;
            default:
                break;
        }
    }

    class ChannelListGridAdapter extends RecyclerView.Adapter<ChannelListGridAdapter.LinearViewHolder> {
        private String TAG = "rich---ChannelListGridAdapter";

        ChannelListGridAdapter() {

        }

        @Override
        public int getItemCount() {
            Log.d(TAG, "getItemCount");
            return channelModels.size();
        }

        @NonNull
        @Override
        public ChannelListGridAdapter.LinearViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Log.d(TAG, "onCreateViewHolder");
            return new ChannelListGridAdapter.LinearViewHolder(LayoutInflater.from(mContext).inflate
                    (R.layout.item_rv_channel_list, parent, false));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final ChannelListGridAdapter.LinearViewHolder holder, @SuppressLint("RecyclerView") final int position) {
            Log.d(TAG, "onBindViewHolder");
            if (channelModels.size() == 0) {
                return;
            }
            holder.channelDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (dmrManager.getTransmitFrequency() == channelModels.get(position).getTxChannel() &&
                            dmrManager.getReceiveFrequency() == channelModels.get(position).getRxChannel()) {
                        Toast.makeText(mContext, "Current channel can't delete", Toast.LENGTH_SHORT).show();
                    } else {
                        mDataBaseUtils.deleteChannelById(channelModels.get(position).getId());
                        channelModels.clear();
                        channelModels.addAll(mDataBaseUtils.findChannelList());
                        notifyDataSetChanged();
                    }
                }
            });

            holder.channelItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    dmrManager.setReceiveFrequency(channelModels.get(position).getRxChannel());
                    dmrManager.setTransmitFrequency(channelModels.get(position).getTxChannel());
                    dmrManager.setColorCode(channelModels.get(position).getColorCode());

                    dmrManager.setInboundSlot(channelModels.get(position).getTimeSlot());
                    dmrManager.setOutbountSlot(channelModels.get(position).getTimeSlot());
                    dmrManager.setPower(channelModels.get(position).getPower());
                    dmrManager.flush();
                    mSpeech.speak(channelModels.get(position).getNameChannel(), TextToSpeech.QUEUE_FLUSH, null);
                    //SoundPoolUtils.getInstance(mContext).playSound(false);
                    notifyDataSetChanged();
                }
            });

            if (dmrManager.getTransmitFrequency() == channelModels.get(position).getTxChannel() &&
                    dmrManager.getReceiveFrequency() == channelModels.get(position).getRxChannel()) {
                holder.channelName.setTextColor(Color.RED);
                holder.channelShowOnline.setBackgroundResource(R.drawable.shape_online);
            } else {
                holder.channelName.setTextColor(Color.WHITE);
                //holder.channelName.setTextColor(Color.DKGRAY);
                holder.channelShowOnline.setBackgroundResource(R.drawable.shape_setting_offline);
            }
            //holder.channelColor.setText(String.valueOf(channelModels.get(position).getColorCode()));
            if(channelModels.get(position).getTimeSlot() == 1){
                holder.channelSlot.setText("B");
                holder.channelSlotImg.setImageResource(R.mipmap.out_slot_big);
            }else {
                holder.channelSlot.setText("A");
                holder.channelSlotImg.setImageResource(R.mipmap.in_slot_big);
            }
            if(channelModels.get(position).getPower() == 1){
                holder.channelPower.setImageResource(R.mipmap.h_power_b);
            }else{
                holder.channelPower.setImageResource(R.mipmap.l_power_b);
            }
            holder.channelName.setText(channelModels.get(position).getNameChannel());
            holder.channelTx.setText("Tx:" + ConvertUtils.div(channelModels.get(position).getTxChannel(), 1000000));
            holder.channelRx.setText("Rx:" + ConvertUtils.div(channelModels.get(position).getRxChannel(), 1000000));
        }

        public class LinearViewHolder extends RecyclerView.ViewHolder {
            private TextView channelName;
            private TextView channelTx;
            private TextView channelRx;
            private TextView channelColor;
            private TextView channelSlot;
            private ImageView channelSlotImg;
            private ImageView channelPower;
            private TextView channelShowOnline;
            private ImageView channelDelete;
            private LinearLayout channelItem;

            private LinearViewHolder(View itemView) {
                super(itemView);
                channelName = itemView.findViewById(R.id.channel_name);
                channelTx = itemView.findViewById(R.id.channel_tx);
                channelRx = itemView.findViewById(R.id.channel_rx);
                channelColor = itemView.findViewById(R.id.channel_color);
                channelSlot = itemView.findViewById(R.id.channel_slot);
                channelSlotImg = itemView.findViewById(R.id.channel_slot_img);
                channelPower = itemView.findViewById(R.id.channel_power);
                channelShowOnline = itemView.findViewById(R.id.channel_show_online);
                channelDelete = itemView.findViewById(R.id.channel_delete);
                channelItem = itemView.findViewById(R.id.rv_item_view);
            }
        }

    }

    private void initDialog() {
        final CommonDialog dialog = new CommonDialog(mContext);
        dialog.setNickName("Channel")
                .setNickId("Tx")
                .setNickExtId("Rx")
                .setTitle("Create Channel")
                .setSingle(false).setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                String channelName = dialog.getCommonName().getText().toString();
                String txFre = dialog.getCommonId().getText().toString();
                String rxFre = dialog.getCommonExtId().getText().toString();
                if (!TextUtils.isEmpty(channelName) && !TextUtils.isEmpty(txFre) && !TextUtils.isEmpty(rxFre)) {

                    if (!ConvertUtils.isNumeric(txFre) || !ConvertUtils.isNumeric(rxFre)) {
                        Toast.makeText(mContext, "Tx is not number.", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    int mTxFreqVal = (int) (Double.valueOf(txFre.trim()) * 1000000);
                    if (mTxFreqVal < 400000000 || mTxFreqVal > 480000000) {
                        Toast.makeText(mContext, "Tx invalid.", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if ((mTxFreqVal % 12500) != 0) {
                        Toast.makeText(mContext, "Tx invalid.", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    int mRxFreqVal = (int) (Double.valueOf(rxFre.trim()) * 1000000);
                    if (mRxFreqVal < 400000000 || mRxFreqVal > 480000000) {
                        Toast.makeText(mContext, "Rx invalid.", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if ((mRxFreqVal % 12500) != 0) {
                        Toast.makeText(mContext, "Rx invalid.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    int count = mDataBaseUtils.findChannel(mTxFreqVal,mRxFreqVal);
                    if (count > 0) {
                        Toast.makeText(mContext, "Channel already exist.", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    mDataBaseUtils.insertChannel(channelName, mTxFreqVal, mRxFreqVal);
                    channelModels.clear();
                    channelModels.addAll(mDataBaseUtils.findChannelList());
                    adapter.notifyDataSetChanged();
                    Toast.makeText(mContext, "Save success.", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                } else {
                    Toast.makeText(mContext, "data is null.", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onNegativeClick() {
                dialog.dismiss();
                Toast.makeText(mContext, "cancel", Toast.LENGTH_SHORT).show();
            }
        }).show();
    }

    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                Log.i(TAG, "onInit: TTS init success");
            }
            else{
                Log.i(TAG, "onInit: TTS init fail");
            }
        }
    }
}
